package com.hdc.hdc.mainmenu2.mail;

import java.net.ConnectException;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.hdc.hdc.mainmenu2.entity.vo.MailMessageVO;
import com.hdc.hdc.mainmenu2.util.ReturnJson;

import freemarker.template.Template;

/**
 * 邮件发送
 * @author GJY
 * 人生格言：学以致用终将成功
 * @version 创建时间：2018年4月9日 下午3:41:30 
 *
 */
@Component
public class MailHelp {
	
	
	private static final Logger log = LoggerFactory.getLogger(MailHelp.class);
	
	@Autowired
    private JavaMailSender mailSender; //自动注入的Bean

	@Value("${spring.mail.username}")
    private String Sender; //读取配置文件中的参数
	
	@Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;  //自动注入
	
	@SuppressWarnings("unchecked")
	public ReturnJson sendEmailToCustomer(MailMessageVO vo) {
		
		log.info("邮件功能发起.......................");
		
		ReturnJson j = new ReturnJson();
		
		MimeMessage message = null;
		
		try {
            message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(Sender);
            helper.setTo("gjy20wan@163.com");
            helper.setSubject("主题：通知邮件");

			Map<String, Object> model = new HashedMap();
            model.put("username", "jk");
            model.put("vo", vo);

            //读取 html 模板
            Template template = freeMarkerConfigurer.getConfiguration().getTemplate("/contact/mail.html");
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
            helper.setText(html, true);
            
            j = j.ok("谢谢您的关注，我们将最快的速度联系您!");
            
            log.info("邮件功能发送");
            mailSender.send(message);
        } catch (Exception e) {
        	log.error("邮件功能异常。。。。。。。。。。。。。。。。。。");
        	e.printStackTrace();
        	if(e instanceof ConnectException) {
        		log.info("连接超时，重新发起邮件发送功能");
        		mailSender.send(message);
        	}else {
        		log.error("邮件功能异常："+e.getMessage());
        		j = j.fail("提交失败，请手动发送邮箱或者打电话到上面显示的联系方式。非常抱歉");
        		
        	}
        	
        }
		
		return j;
	}

}
